﻿
using System.Collections.Generic;
using System.Data;
using System;
using System.IO;
using System.Net;
using System.Text;
using SXT.Party.MSPeopleTestWcfService;
namespace ZHDJ.MobileInterface
{
    public partial class GetPeopleTestList : AbstractBasePage
    {
        protected override OutParam BusinessProcess<InParam, OutParam>(InParam inParam)
        {
            // 业务逻辑返回的响应对象  
            GetPeopleTestListOutParam result = new GetPeopleTestListOutParam();
            GetPeopleTestListInParam param = new GetPeopleTestListInParam();
            string logMsg = "";
            bool isFlag = true;
            string userName = "";
                 
            try
            { 
                param = inParam as GetPeopleTestListInParam;
                if (string.IsNullOrEmpty(param.user_id))
                {
                    result.code = "0";
                    result.desc = "用户不能为空";

                    isFlag = false;
                }


                if (CommonUtils.IsDisableUsers(param.user_id))
                {
                    result.code = "0";
                    result.desc = "用户状态有问题，请联系管理员";

                    isFlag = false;
                }
                DataSet dsUser = new DataSet(); 
                if (isFlag)
                {
                    dsUser = InterfaceHelper.GetMembersByFilter(" LoginID='" + param.user_id + "' ");

                    if (dsUser == null || dsUser.Tables[0].Rows.Count == 0)
                    {
                        result.code = "0";
                        result.desc = "用户不存在";

                        isFlag = false;
                    }
                    else
                    {
                        userName = dsUser.Tables[0].Rows[0]["userName"].ToString();
                    }
                }     

                if (isFlag)
                { 
                    //获取token  
                    string reader = "";
                    try
                    {
                        IPeopleTestService pts = new PeopleTestServiceClient();
                        reader = pts.ReturnStringResult("http://api.talebase.com/auth/access_token",
                                       string.Format("client_id=UOMdjuEGLqI=&user_id={0}&user_name={1}", param.user_id, userName)).Trim();
                        logMsg += reader;
                        reader = reader.Replace("æ", "").Trim();
                        CPTokenIDInParamEx tokenInfo = SerializeHelper.JsonDeserialize<CPTokenIDInParamEx>(reader);
                        if (tokenInfo != null && tokenInfo.data != null && !string.IsNullOrEmpty(tokenInfo.data.token_id))
                        {
                            result.url = string.Format("{2}?user_id={0}&customer_id=582&token_id={1}",
                                param.user_id, tokenInfo.data.token_id, ServiceSettings.APCPAppURl); 
                        }
                        else
                        {
                            result.code = "0";
                            result.desc = "测评系统登陆失败"; 
                        } 
                    }
                    catch (Exception ex)
                    {
                        result.code = "0";
                        result.desc = "连接测评系统异常";
                        logMsg += ex.Message + ":" + ex.StackTrace;
                    }
                }

                logMsg += result.desc;
            }
            catch (Exception ex)
            {
                result.code = "0";
                result.desc = "操作异常，多次出现请联系管理员"; 
                logMsg += ex.Message + ":" + ex.StackTrace;
            }

            CommonUtils.InsertMobileInterfaceLog(SystemCode +"-GetPeopleTestList", SerializeHelper.JsonSerializer<GetPeopleTestListInParam>(param), logMsg); 
            return result as OutParam;
        }

        protected void Page_Load(object sender, System.EventArgs e)
        {
            if (string.Compare(Request.QueryString["Safe"], "False", true) == 0)
                ProcessRequest<GetPeopleTestListInParam, GetPeopleTestListOutParam>();
            else
                SafeProcessRequest<GetPeopleTestListInParam, GetPeopleTestListOutParam>();
        }

        /// <summary>
        /// Post数据到网站
        /// </summary>
        /// <param name="posturl">网址</param>
        /// <param name="postData">参数</param>
        /// <returns></returns>
        public string GetPage(string posturl, string postData)
        {
            Stream outstream = null;
            Stream instream = null;
            StreamReader sr = null;

            HttpWebResponse response = null;
            HttpWebRequest request = null;
            Encoding encoding = System.Text.Encoding.GetEncoding("UTF-8");
            byte[] data = encoding.GetBytes(postData);
            // 准备请求...
            try
            {
                WebRequest.DefaultWebProxy = WebRequest.GetSystemWebProxy();
                // 设置参数
                request = WebRequest.Create(posturl) as HttpWebRequest;

                CookieContainer cookieContainer = new CookieContainer();
                request.CookieContainer = cookieContainer;
                request.AllowAutoRedirect = true;
                request.Method = "POST";

                request.ContentType = "application/x-www-form-urlencoded";
                request.ContentLength = data.Length;
                outstream = request.GetRequestStream();
                outstream.Write(data, 0, data.Length);
                outstream.Close();
                //发送请求并获取相应回应数据
                response = request.GetResponse() as HttpWebResponse;
                //直到request.GetResponse()程序才开始向目标网页发送Post请求
                instream = response.GetResponseStream();
                sr = new StreamReader(instream, encoding);
                //返回结果网页（html）代码
                string content = sr.ReadToEnd();
                string err = string.Empty;
                return content;
            }
            catch (Exception ex)
            {
                string err = ex.Message;
                return err;
            }
        }
    }

    #region 请求参数
    public class GetPeopleTestListInParam
    { 
        /// <summary>
        ///	用户ID	 
        /// </summary>
        public string user_id
        { get; set; }   

        /// <summary>
        ///	客户端类型	Android或iPhone
        /// </summary>
        public string ClientType
        { get; set; } 
    }
    #endregion

    #region 结果参数
    public class GetPeopleTestListOutParam
    {
        public GetPeopleTestListOutParam()
        {
            code = "1";
            desc = "操作成功"; 
        }

        /// <summary>
        /// 返回结果 具体见接口返回对照码 1	成功 0	失败 2	请求非法 加密结果和传入的MD5字符串进行比较，如果相同则执行接口操作，否则返回1001错误响应码
        /// </summary>
        public string code
        { get; set; }

        /// <summary>
        /// 结果描述 成功和失败都需要
        /// </summary>
        public string desc
        { get; set; }

        /// <summary>
        /// 人才测评url
        /// </summary>
        public string url
        { get; set; } 
    }

    public class CPTokenIDInParamEx
    {
        public CPTokenIDInParamEx()
        {
            data = new CPTokenInfoEx();
        }

        public string status { get; set; }
        public string error_code { get; set; }
        public string error_message { get; set; }
        public string message { get; set; }
        public string url { get; set; }

        public CPTokenInfoEx data { get; set; }
    }
    public class CPTokenInfoEx
    {
        public string token_id { get; set; }
        public string expires_in { get; set; }
        public string customer_id { get; set; }
    }
    #endregion 
}